<template>
  <div>
    <!-- 面包屑导航 -->
    <el-breadcrumb separator-class="el-icon-arrow-right">
      <el-breadcrumb-item :to="{ path: '/home' }">首页</el-breadcrumb-item>
      <el-breadcrumb-item>权限管理</el-breadcrumb-item>
      <el-breadcrumb-item>角色列表</el-breadcrumb-item>
    </el-breadcrumb>
    <!-- 卡片视图 -->
    <el-card>
      <!-- 添加角色按钮区域 -->
      <el-row>
        <el-col>
          <el-button type="primary" @click="dialogVisible = true"
            >添加角色</el-button
          >
        </el-col>
      </el-row>

      <!-- 角色列表区域 -->
      <el-table :data="roleList" border stripe>
        <!-- 扩展列 -->
        <el-table-column type="expand">
          <template v-slot="scope">
            <el-row
              v-for="(item1, i1) in scope.row.children"
              :key="item1.id"
              :class="['bdbottom', i1 === 0 ? 'bdtop' : '', 'vcenter']"
            >
              <!-- 渲染一级权限 -->
              <el-col :span="5"
                ><el-tag
                  closable
                  @close="removeRoleById(scope.row, item1.id)"
                  >{{ item1.authName }}</el-tag
                ><i class="el-icon-caret-right"></i
              ></el-col>
              <!-- 渲染二级和三级权限 -->
              <el-col :span="19">
                <el-row
                  :class="[i2 === 0 ? '' : 'bdtop', 'vcenter']"
                  v-for="(item2, i2) in item1.children"
                  :key="item2.id"
                >
                  <el-col :span="6">
                    <el-tag
                      type="success"
                      closable
                      @close="removeRoleById(scope.row, item2.id)"
                      >{{ item2.authName }}</el-tag
                    >
                    <i class="el-icon-caret-right"></i>
                  </el-col>
                  <!-- 三级权限 -->
                  <el-col :span="18">
                    <el-tag
                      type="warning"
                      v-for="item3 in item2.children"
                      :key="item3.id"
                      closable
                      @close="removeRoleById(scope.row, item3.id)"
                      >{{ item3.authName }}</el-tag
                    >
                  </el-col>
                </el-row>
              </el-col>
            </el-row>
            <!-- <pre>
              {{ scope.row }}
            </pre> -->
          </template>
        </el-table-column>
        <!-- 索引列 -->
        <el-table-column type="index" label="#"></el-table-column>
        <el-table-column label="角色名称" prop="roleName"></el-table-column>
        <el-table-column label="角色描述" prop="roleDesc"></el-table-column>
        <el-table-column label="操作" width="300px">
          <template v-slot="scope">
            <el-button
              size="mini"
              type="primary"
              icon="el-icon-search"
              @click="showEditDialog(scope.row.id)"
              >编辑</el-button
            >
            <el-button
              size="mini"
              type="danger"
              icon="el-icon-delete"
              @click="removeUserById(scope.row.id)"
              >删除</el-button
            >
            <el-button
              size="mini"
              type="warning"
              icon="el-icon-setting"
              @click="showRightDialog(scope.row)"
              >分配权限</el-button
            >
          </template>
        </el-table-column>
      </el-table>
    </el-card>

    <!-- 添加角色对话框 -->
    <el-dialog
      title="提示"
      :visible.sync="dialogVisible"
      width="55%"
      @close="addDialogClosed"
    >
      <!-- 内容主体区域 -->
      <el-form :model="addRole" ref="addRoleRef" label-width="70px">
        <el-form-item label="角色名称" prop="roleName">
          <el-input v-model="addRole.roleName"></el-input>
        </el-form-item>
        <el-form-item label="角色描述" prop="roleDesc">
          <el-input v-model="addRole.roleDesc"></el-input>
        </el-form-item>
      </el-form>
      <!-- 底部区域 -->
      <span slot="footer">
        <el-button @click="dialogVisible = false">取 消</el-button>
        <el-button type="primary" @click="addRoles">确 定</el-button>
      </span>
    </el-dialog>

    <!-- 修改角色的对话框 -->
    <el-dialog
      title="修改角色"
      :visible.sync="editDialogVisible"
      width="50%"
      @close="editDialogClosed"
    >
      <el-form :model="editForm" ref="editFormRef" label-width="70px">
        <el-form-item label="角色名称" prop="roleName">
          <el-input v-model="editForm.roleName"></el-input>
        </el-form-item>
        <el-form-item label="角色描述" prop="reoleDesc">
          <el-input v-model="editForm.roleDesc"></el-input>
        </el-form-item>
      </el-form>
      <span slot="footer" class="dialog-footer">
        <el-button @click="editDialogVisible = false">取 消</el-button>
        <el-button type="primary" @click="editUserInfo">确 定</el-button>
      </span>
    </el-dialog>

    <!-- 分配权限的对话框 -->
    <el-dialog
      title="分配权限"
      :visible.sync="rightDialogVisible"
      width="50%"
      @close="rightDialogClosed"
    >
      <!-- 树形控件 -->
      <el-tree
        :data="rightList"
        :props="treeProps"
        show-checkbox
        default-expand-all
        node-key="id"
        :default-checked-keys="dekeys"
        ref="treeRef"
      ></el-tree>
      <span slot="footer" class="dialog-footer">
        <el-button @click="rightDialogVisible = false">取 消</el-button>
        <el-button type="primary" @click="allotRight">确 定</el-button>
      </span>
    </el-dialog>
  </div>
</template>

<script>
export default {
  data() {
    return {
      roleList: [],
      // 对话框的显示与隐藏
      dialogVisible: false,
      // 控制修改用户对话框的显示与隐藏
      editDialogVisible: false,
      //定义编辑得到的数据
      editForm: {},
      addRole: {
        roleName: "",
        roleDesc: "",
      },
      // 分配权限的显示隐藏
      rightDialogVisible: false,
      // 分配权限数据
      rightList: [],
      // 树形控件的属性绑定对象
      treeProps: {
        label: "authName",
        children: "children",
      },
      // 默认选中节点id数值
      dekeys: [],
      roleId: ''
    };
  },
  created() {
    this.getRoleList();
  },

  methods: {
    async getRoleList() {
      const { data: res } = await this.$http.get("roles");

      if (res.meta.status !== 200) {
        return this.$message.error("获取角色列表失败");
      }
      console.log(res.data);
      this.roleList = res.data;
    },

    // 展示编辑角色对话框
    async showEditDialog(id) {
      console.log(id);
      this.editDialogVisible = true;
      const { data: res } = await this.$http.get("roles/" + id);

      if (res.meta.status !== 200) {
        console.log(res);
        return this.$message.error("编辑角色失败");
      }
      this.editForm = res.data;
      // console.log(this.editForm);
    },
    // 修改用户对话框的关闭事件
    editDialogClosed() {
      this.$refs.editFormRef.resetFields();
    },
    // 点击确定修改角色信息,就提交
    async editUserInfo() {
      const { data: res } = await this.$http.put(
        "roles/" + this.editForm.roleId,
        {
          roleName: this.editForm.roleName,
          roleDesc: this.editForm.roleDesc,
        }
      );
      console.log(res);

      if (res.meta.status !== 200) {
        return this.$message.error("修改角色失败");
      }
      // 提示修改成功
      this.$message.success("修改成功");
      // 重新获取列表
      this.getRoleList();
      // 隐藏对话框
      this.editDialogVisible = false;
    },
    async removeUserById(id) {
      // 弹框询问用户是否删除数据

      const confirmResult = await this.$confirm(
        "此操作将永久删除该用户, 是否继续?",
        "提示",
        {
          confirmButtonText: "确定",
          cancelButtonText: "取消",
          type: "warning",
        }
      ).catch((err) => err);

      // 如果用户确认了删除, 则返回值为字符串 confirm
      //  如果用户取消了删除,则返回字符串 cancel
      if (confirmResult !== "confirm") {
        return this.$message.info("取消了删除");
      }

      const { data: res } = await this.$http.delete("roles/" + id);
      if (res.meta.status !== 200) {
        return this.$message.error("删除失败");
      }
      this.$message.success("删除成功");
      // 更新列表
      this.getRoleList();
    },
    // 点击确定添加角色
    async addRoles() {
      const { data: res } = await this.$http.post("roles", this.addRole);
      if (res.meta.status !== 201) {
        return this.$message.error("添加角色失败");
      }
      this.$message.success("添加角色成功");
      // 隐藏对话框
      this.dialogVisible = false;
      // 更新列表
      this.getRoleList();
    },
    // 监听添加角色对话框关闭的事件
    addDialogClosed() {
      this.$refs.addRoleRef.resetFields();
    },
    //删除三级权限
    async removeRoleById(role, rightId) {
      console.log(role, rightId);
      // messageBox提示用户是否删除
      const confirmResult = await this.$confirm(
        "此操作将永久删除该文件, 是否继续?",
        "提示",
        {
          confirmButtonText: "确定",
          cancelButtonText: "取消",
          type: "warning",
        }
      ).catch((err) => err);
      if (confirmResult !== "confirm") {
        return this.$message.info("取消了删除");
      }
      const { data: res } = await this.$http.delete(
        `roles/${role.id}/rights/${rightId}`
      );
      if (res.meta.status !== 200) {
        return this.$message.error("删除权限失败");
      }
      this.$message.success("已删除权限");
      // 更新列表,这个更新会重新渲染导致得再打开一次扩展
      //this.getRoleList();
      role.children = res.data;
    },
    // 权限分配
    async showRightDialog(role) {
      // 获取角色Id
      this.roleId = role.id
      // 获取分配权限数据
      const { data: res } = await this.$http.get("rights/tree");
      if (res.meta.status !== 200) {
        return this.$message.error("获取分配权限失败");
      }
      // 将数据存在data中
      this.rightList = res.data;
      // this.$message.success('获取分配权限')
      console.log(this.rightList);
      //  递归获取三级节点的Id
      this.getLeafKeys(role, this.dekeys);

      // 将分配权限的对话框显示
      this.rightDialogVisible = true;
    },
    // 通过递归的形式, 获取角色下所有三级权限的id,并保存到defkeys数组中
    getLeafKeys(node, arr) {
      if (!node.children) {
        return arr.push(node.id);
      }
      node.children.forEach((item) => {
        this.getLeafKeys(item, arr);
      });
    },
    // 监听分配权限对话框关闭的事件
    rightDialogClosed() {
      this.dekeys = [];
    },
    // 点击确定为角色分配权限
    async allotRight() {
      const arr = [...this.$refs.treeRef.getCheckedKeys(),...this.$refs.treeRef.getHalfCheckedKeys()]
      const strTree = arr.join(',')
      console.log(this.roleList);
      const {data: res} = await this.$http.post(`roles/${this.roleId}/rights`,{rids: strTree})
      if(res.meta.status !== 200) {
        return this.$message.error('角色授权失败')
      }
      this.$message.success('角色授权成功')
      this.getRoleList()
      this.rightDialogVisible= false
    }
  },
};
</script>

<style lang="less" scoped></style>
